package com.meitianhui.convenitenbuy.module.wallet.ui;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseFragment;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.ui.MainActivity;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.AdWebViewActivity;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.MemberRulesWebViewActivity;
import com.meitianhui.convenitenbuy.module.mine.model.UserAsset;
import com.meitianhui.convenitenbuy.module.wallet.contract.WalletContract;
import com.meitianhui.convenitenbuy.module.wallet.di.DaggerWalletComponent;
import com.meitianhui.convenitenbuy.module.wallet.di.WalletModule;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.UserPropertyBean;
import com.meitianhui.convenitenbuy.module.wallet.presenter.WalletPresenter;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletChangeActivity;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletCouponActivity;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletFamilyCardsActivity;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletGoldActivity;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletPaymentActivity;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletPointsActivity;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletRedPacketsActivity;
import com.meitianhui.convenitenbuy.module.wallet.ui.activity.WalletScanningActivity;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.widget.Spanny;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/10/30.
 */

public class WalletFragment extends BaseFragment implements WalletContract.View, SwipeRefreshLayout.OnRefreshListener {
    public static final String Tag = WalletFragment.class.getSimpleName();
    SwipeRefreshLayout mSwipeRefresh;
    TextView mTvScanning;
    TextView mTvPaymentCode;
    LinearLayout mLlLooseChange;
    TextView mTvLooseChange;
    LinearLayout mLlGoldCoins;
    TextView mTvGoldCoins;
    LinearLayout mLlAccumulatePoints;
    TextView mTvAccumulatePoints;
    RelativeLayout mRlMemberBenefits;
    TextView mTvMemberBenefits;
    RelativeLayout mRlRedPackets;
    TextView mTvRedPackets;
    RelativeLayout mRlFamilyCards;
    TextView mTvFamilyCards;
    RelativeLayout mRlWalletCoupon;
    TextView mTvWalletCoupon;
    LinearLayout mLlRecharge;
    MainActivity mActivity;
    UserPropertyBean mPropertyBean;
    UserAsset mAssetBean;

    @Inject
    WalletPresenter presenter;

    @Override
    protected int getLayout() {
        return R.layout.fragment_wallet;
    }

    @Override
    protected void initView(LayoutInflater inflater) {
        super.initView(inflater);
        DaggerWalletComponent.builder().appComponent(App.getInstance().getAppComponent()).walletModule(new WalletModule(this)).build().inject(this);
        mActivity = (MainActivity) getActivity();
        initId();
        getUserAssetSuccess(InfoProvider.getUserAsset(App.getInstance()));
        getInformation();
        registerPush();
    }

    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean bean) throws Exception {
                if (bean != null) {
                    if (bean.type == Constants.EVENT_TYPE_REFRESH) {
                        getInformation();
                    } else if (bean.type == Constants.EVENT_TYPE_LOGIN_SUCCESS) {
                        getInformation();
                    }
                }
            }
        });

        Disposable subscribe1 = RxBus.get().toFlowable(PayResultBean.class).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean bean) throws Exception {
                if (bean != null) {
                    if (bean.result == Constants.PAY_RESULT_SUCCESS) {
                        getInformation();
                    }
                }
            }
        });


        mCompositeDisposable.add(subscribe);
        mCompositeDisposable.add(subscribe1);


    }

    /**
     * 初始化id。
     */
    private void initId() {
        mSwipeRefresh = (SwipeRefreshLayout) getViewById(R.id.swipe_refresh_wallet);
        mTvScanning = (TextView) getViewById(R.id.tv_wallet_scanning);
        mTvPaymentCode = (TextView) getViewById(R.id.tv_wallet_payment_code);
        mLlLooseChange = (LinearLayout) getViewById(R.id.ll_wallet_loose_change);
        mTvLooseChange = (TextView) getViewById(R.id.tv_wallet_loose_change);
        mLlGoldCoins = (LinearLayout) getViewById(R.id.ll_wallet_gold_coins);
        mTvGoldCoins = (TextView) getViewById(R.id.tv_wallet_gold_coins);
        mLlAccumulatePoints = (LinearLayout) getViewById(R.id.ll_wallet_accumulate_points);
        mTvAccumulatePoints = (TextView) getViewById(R.id.tv_wallet_accumulate_points);
        mRlMemberBenefits = (RelativeLayout) getViewById(R.id.rl_wallet_member_benefits);
        mTvMemberBenefits = (TextView) getViewById(R.id.tv_wallet_member_benefits);
        mRlRedPackets = (RelativeLayout) getViewById(R.id.rl_wallet_red_packets);
        mTvRedPackets = (TextView) getViewById(R.id.tv_wallet_red_packets);
        mRlFamilyCards = (RelativeLayout) getViewById(R.id.rl_wallet_family_cards);
        mTvFamilyCards = (TextView) getViewById(R.id.tv_wallet_family_cards);
        mRlWalletCoupon = (RelativeLayout) getViewById(R.id.rl_wallet_coupon);
        mTvWalletCoupon = (TextView) getViewById(R.id.tv_wallet_coupon);
        mLlRecharge = (LinearLayout) getViewById(R.id.ll_wallet_recharge);

        RxUtils.bindEvents(mTvScanning, this);
        RxUtils.bindEvents(mTvPaymentCode, this);
        RxUtils.bindEvents(mLlLooseChange, this);
        RxUtils.bindEvents(mLlGoldCoins, this);
        RxUtils.bindEvents(mLlAccumulatePoints, this);
        RxUtils.bindEvents(mRlMemberBenefits, this);
        RxUtils.bindEvents(mRlRedPackets, this);
        RxUtils.bindEvents(mRlFamilyCards, this);
        RxUtils.bindEvents(mRlWalletCoupon, this);
        RxUtils.bindEvents(mLlRecharge, this);
        mSwipeRefresh.setOnRefreshListener(this);

    }

    /**
     * 获取用户信息
     */
    private void getInformation() {
        presenter.getUserAsset();
        presenter.getUserProperty();
    }

    /**
     * 显示用户财产
     *
     * @param userAsset
     */
    private void showAssetInfo(UserAsset userAsset) {
        convertChange(userAsset.getCash_balance());
        mTvGoldCoins.setText(TextUtils.isEmpty(userAsset.getGold()) ? "0" : userAsset.getGold());
        mTvAccumulatePoints.setText(TextUtils.isEmpty(userAsset.getBonus()) ? "0" : userAsset.getBonus());

    }

    /**
     * 显示用户资产
     *
     * @param bean
     */
    private void showPropertyInfo(UserPropertyBean bean) {
        if (bean != null) {
            mTvMemberBenefits.setText(TextUtils.isEmpty(bean.getBenefit_num()) ? getString(R.string.wallet_zero) : bean.getBenefit_num());
            mTvRedPackets.setText(TextUtils.isEmpty(bean.getLucky_money_num()) ? getString(R.string.wallet_zero) : bean.getLucky_money_num());
            mTvFamilyCards.setText(TextUtils.isEmpty(bean.getCard_num()) ? getString(R.string.wallet_zero) : bean.getCard_num());
            mTvWalletCoupon.setText(TextUtils.isEmpty(bean.getCoupon_num()) ? getString(R.string.wallet_zero) : bean.getCoupon_num());
        }
    }

    /**
     * 转换零钱格式
     *
     * @param looseChange
     */
    private void convertChange(String looseChange) {
        String number;
        String decimal;
        if (looseChange.contains(".")) {
            int i = looseChange.indexOf(".");
            number = looseChange.substring(0, i);
            decimal = looseChange.substring(i);
        } else {
            number = looseChange;
            decimal = ".00";
        }
        Spanny spanny = new Spanny(number, new TextAppearanceSpan(
                mActivity, R.style.red_big_text_balance))
                .append(decimal, new TextAppearanceSpan(mActivity, R.style.red_small_text_balance));
        mTvLooseChange.setText(spanny);
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.tv_wallet_scanning:
                Intent i = new Intent(getActivity(), WalletScanningActivity.class);
                getActivity().startActivity(i);
                break;
            case R.id.tv_wallet_payment_code:
                JumpUtil.jumpToWalletActivity(getActivity(), WalletPaymentActivity.class, mAssetBean);
                break;
            case R.id.ll_wallet_loose_change:
                JumpUtil.jumpToWalletActivity(getActivity(), WalletChangeActivity.class, mAssetBean);
                break;
            case R.id.ll_wallet_gold_coins:
                JumpUtil.jumpToWalletActivity(getActivity(), WalletGoldActivity.class, mAssetBean);
                break;
            case R.id.ll_wallet_accumulate_points:
                JumpUtil.jumpToWalletActivity(getActivity(), WalletPointsActivity.class, mAssetBean);
                break;
            case R.id.rl_wallet_member_benefits:
                clickBenefits();
                break;
            case R.id.rl_wallet_red_packets:
                JumpUtil.jumpToWalletActivity(getActivity(), WalletRedPacketsActivity.class, mPropertyBean);
                break;
            case R.id.rl_wallet_family_cards:
                JumpUtil.jumpToWalletActivity(getActivity(), WalletFamilyCardsActivity.class, mPropertyBean);
                break;
            case R.id.rl_wallet_coupon:
                JumpUtil.jumpToWalletActivity(getActivity(), WalletCouponActivity.class, mPropertyBean);
                break;
            case R.id.ll_wallet_recharge:
                Intent intent = new Intent(getActivity(), AdWebViewActivity.class);
                intent.putExtra("url", Constants.HOST + "h5/common/mobile-fee"
                        + "?member_id=" + InfoProvider.getUserToken(App.getInstance()).getMember_id() + "&member_type_key=consumer");
                intent.putExtra("title", "话费充值");
                startActivity(intent);
                break;
        }
    }

    private void clickBenefits() {
        String memberId = InfoProvider.getUserToken(App.getInstance()).getMember_id();
        String mobile = InfoProvider.getUserToken(App.getInstance()).getMobile();
        Intent intent = new Intent(getActivity(), MemberRulesWebViewActivity.class);
        intent.putExtra("url", Constants.HOST + "h5/c/interests"
                + "?member_id=" + memberId + "&mobile=" + mobile);
        intent.putExtra("title", "会员权益");
        intent.putExtra("member_id", memberId);
        intent.putExtra("mobile", mobile);
        startActivity(intent);
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void updateBack() {

    }

    @Override
    public void getUserAssetSuccess(UserAsset bean) {
        mAssetBean = bean;
        if (bean != null)
            showAssetInfo(bean);
        if (mSwipeRefresh.isRefreshing())
            mSwipeRefresh.setRefreshing(false);
    }

    @Override
    public void getUserPropertySuccess(UserPropertyBean bean) {
        mPropertyBean = bean;
        if (bean != null)
            showPropertyInfo(bean);
        if (mSwipeRefresh.isRefreshing())
            mSwipeRefresh.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        getInformation();
    }
}
